/**
 * 2023.02025 更名为bspDailyClickStatisticsJob 避免与mis包从冲突
 */

package com.topscomm.base.xxljob;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.topscomm.base.pojo.BaseModuleLogDailyStatisticsEntity;
import com.topscomm.base.service.IBaseModuleLogDailyStatisticsService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboItemDetailsEntity;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.cbo.service.ICboModuleLogService;
import com.topscomm.cbo.service.ICboModuleService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.common.ParameterCache;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@JobHandler("bspDailyClickStatisticsJob")
@Component
public class bspDailyClickStatisticsJob extends IJobHandler {
    @Autowired
    private IBaseModuleLogDailyStatisticsService baseModuleLogDailyStatisticsService;
    @Autowired
    private ICboUserService cboUserService;
    @Autowired
    private ICboModuleService cboModuleService;
    @Autowired
    private ICboItemDetailsService cboItemDetailsService;

    public ReturnT<String> dailyClickStatisticsJob(String param, Map<String, Object> itemParam) {
        String dateStr = "";
        if (StrUtil.isEmpty(param)) {
            dateStr = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -1));
            XxlJobLogger.log("未收到来自xxljob调度平台的参数，默认生成昨天的数据。", new Object[0]);
        } else {
            dateStr = param;
        }

        String userQuerySql = itemParam.get("dailyClickUsersSql").toString();
        String modulecodes = itemParam.get("dailyClickModuleCode").toString();
        if (!StrUtil.isEmpty(userQuerySql) && !StrUtil.isEmpty(modulecodes)) {
            new ArrayList();

            List<Map<String, Object>> userList;
            try {
                userList = this.cboUserService.selectExecute(userQuerySql);
            } catch (Exception var10) {
                XxlJobLogger.log("执行查询用户信息的sql失败，请检查‘BspDailyClickUsersSql’配置的sql是否正确", new Object[0]);
                return ReturnT.FAIL;
            }
            //删除统计的当前日期的数据
            this.baseModuleLogDailyStatisticsService.deleteByWhere(BaseModuleLogDailyStatisticsEntity.FieldStatisticdate + "=" + SQLAdapter.toDateLong(dateStr));
            //按照人，模块code进行统计
            StringBufferProxy logSql = new StringBufferProxy();
            logSql.appendSingle(" MODULENAME in ({0}) ", modulecodes);
            logSql.appendSingle(" and OPERATEDATE >= {0} ", SQLAdapter.toDateLong(dateStr));
            logSql.appendSingle(" and OPERATEUSER in (select id from ({0}))", userQuerySql);
            List<Map<String, Object>> moduleLogGroupList = baseModuleLogDailyStatisticsService.queryMapByWhere(logSql.toString(),"getYesterdayLog");
            Map<String, Object> userModuleNumMap = new HashMap<String, Object>();
            moduleLogGroupList.forEach((item) -> {
                userModuleNumMap.put(item.get("operateuser").toString() + item.get("modulename").toString(), item.get("num").toString());
            });

            List<Map<String, Object>> moduleList = this.cboModuleService.queryMapByWhere("code in(" + modulecodes + ")");
            List<BasicEntity> insertList = new ArrayList();
            String finalDateStr = dateStr;
            userList.forEach((userMap) -> {
                moduleList.forEach((module) -> {
                    BaseModuleLogDailyStatisticsEntity misModuleLogDailyStatisticsEntity = new BaseModuleLogDailyStatisticsEntity();
                    misModuleLogDailyStatisticsEntity.setSystem(ConvertUtil.convertToString(itemParam.get("system")));
                    misModuleLogDailyStatisticsEntity.setModulecode(ConvertUtil.convertToString(module.get("code")));
                    misModuleLogDailyStatisticsEntity.setModulename(ConvertUtil.convertToString(module.get("name")));
                    misModuleLogDailyStatisticsEntity.setUrladdress(ConvertUtil.convertToString(module.get("urladdress")));
                    misModuleLogDailyStatisticsEntity.setOperateusercode(ConvertUtil.convertToString(userMap.get("code")));
                    misModuleLogDailyStatisticsEntity.setOperateusername(ConvertUtil.convertToString(userMap.get("name")));
                    misModuleLogDailyStatisticsEntity.setStatisticdate(DateUtil.parseDate(finalDateStr));
                    misModuleLogDailyStatisticsEntity.setWeek(DateUtil.dayOfWeekEnum(DateUtil.parseDate(finalDateStr)).toChinese());
                    if(userModuleNumMap.containsKey(userMap.get("id").toString()+module.get("code").toString())) {
                        misModuleLogDailyStatisticsEntity.setClickcount(ConvertUtil.convertToInt(userModuleNumMap.get(userMap.get("id").toString()+module.get("code").toString())));
                    } else {
                        misModuleLogDailyStatisticsEntity.setClickcount(0);
                    }
                    insertList.add(misModuleLogDailyStatisticsEntity);
                    if (insertList.size() == 100) {
                        this.baseModuleLogDailyStatisticsService.insertBatch(insertList);
                        insertList.clear();
                    }

                });
            });
            this.baseModuleLogDailyStatisticsService.insertBatch(insertList);
            System.out.println(22);
        } else {
            XxlJobLogger.log("未配置‘BspDailyClickUsersSql’或‘BspDailyClickModuleCode’系统参数，不生成点击量统计数据。", new Object[0]);
        }
        return ReturnT.SUCCESS;
    }

    public ReturnT<String> execute(String param) throws Exception {

        List<CboItemDetailsEntity> sysList = cboItemDetailsService.queryByWhere(" itemid in (select id from CboItems where code='ClickStatisticSystemSetting') ");
        for (CboItemDetailsEntity sysItem : sysList) {
            Map<String, Object> itemParam = new HashMap<String, Object>();
            itemParam.put("system", sysItem.getCode());
            itemParam.put("dailyClickUsersSql", sysItem.getExtendfield1());
            itemParam.put("dailyClickModuleCode", sysItem.getExtendfield2());
            this.dailyClickStatisticsJob(param, itemParam);
        }
        return ReturnT.SUCCESS;
    }
}
